package com.learn.sunday.common.service.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.encoders.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
public class DigestUtils {

    public static String md5Hex(String data)  {

        if (StringUtils.isBlank(data)) {
            throw new IllegalArgumentException("MD5 digest param is empty!");
        }

        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("MD5 digest param is empty!");
        }

        return new String(Hex.encode(digest.digest(data.getBytes(java.nio.charset.StandardCharsets.UTF_8))));
    }


    /**
     * 生成认证响应头
     *
     * @return
     */
    public static String generateAuthHeader(int validTime,String realm,String key) {
        long expiryTime = System.currentTimeMillis() + validTime * 1000;
        String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
        String nonceValue = expiryTime + ":" + signatureValue;
        String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes()));
        String authenticateHeader = "Digest realm=\"" + realm + "\", "
                + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\"";
        return authenticateHeader;
    }
}
